package com.hxgz.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "jwt.config")
public class JwtUtil {

  private String key;

  private long ttl;

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public long getTtl() {
    return ttl;
  }

  public void setTtl(long ttl) {
    this.ttl = ttl;
  }

  public String createJWT(String id, String subject, String roles) {
    long nowMillis = System.currentTimeMillis();
    Date date = new Date(nowMillis);
    JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(subject).setIssuedAt(date).signWith(
        SignatureAlgorithm.HS256, key).claim("roles", roles);
    if (ttl > 0) {
      jwtBuilder.setExpiration(new Date(nowMillis + ttl));
    }
    return jwtBuilder.compact();
  }

  public Claims praseJwt(String jwtStr) {
    return Jwts.parser().setSigningKey(key).parseClaimsJws(jwtStr).getBody();
  }

}
